package com.blacktea.webmagic.demo.pipeline;

import cn.hutool.core.map.MapUtil;
import com.blacktea.webmagic.demo.domain.Download;
import com.blacktea.webmagic.demo.strategy.DownloadContext;
import com.overzealous.remark.Remark;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.ResultItems;

import java.util.Map;

/**
 * @description:
 * @author: black tea
 * @date: 2021/9/24 14:12
 */
@Slf4j
@Getter
@Setter
public class MDDownloadPipeline extends AbstractDownloadPipeline{

    private Download download;

    private MDDownloadPipeline() {
    }

    public static MDDownloadPipeline download(Download download) {
        DownloadContext.context(download).ifPresent(context -> context.executCheck(download));
        MDDownloadPipeline mdDownloadPipeline = new MDDownloadPipeline();
        mdDownloadPipeline.setDownload(download);
        return mdDownloadPipeline;
    }

    @Override
    public void download(ResultItems resultItems) {
        Map<String, Object> all = resultItems.getAll();
        if (MapUtil.isNotEmpty(all)){
            StringBuffer buffer = new StringBuffer();
            int size = all.size();
            all.forEach((k,v) -> {
                Remark remark = new Remark();
                String html = remark.convertFragment(String.valueOf(v));
                log.debug("\n当前k:{}->{}\n",k,html);
                buffer.append(html);
                if (1 < size){
                    buffer.append("\n\n--------------------------------------------------------------------\n\n");
                    buffer.append("# md分割-下一篇\n\n");
                }
            });
            DownloadContext.context(download).ifPresent(context -> context.executDownloadMd(download,buffer.toString()));
        }

    }
}
